#coding=utf-8

"""
需要分步提交信息

第一步
提交会议名称
提交会议图片
提交时间、地点

第二步
提交长短介绍

第三步
提交过程
"""
from . import model
from . import perm_valid
from core.error import ServiceError
from datetime import datetime,timedelta


def submit_conference(session,step,uid,creat_identity_id,data,creator_id):
    perm_valid.manager_perm_valid(session, creat_identity_id)
    valid_data = ConferenceValid.verify(data,step)
    if not valid_data:
        return False
    if uid is not None:
        # 更新
        conference_obj = model.MeetingList()
        conference_obj.uid=int(uid)
        conference_obj.meeting_status = step+1
        conference_obj.update_datamap(valid_data)
        conference_obj.save(update_by={"creat_identity_id":int(creat_identity_id)})
        return conference_obj.uid
    else:
        #插入
        conference_obj = model.MeetingList()
        conference_obj.creat_identity_id=creat_identity_id
        conference_obj.creator_id=creator_id
        conference_obj.meeting_status = step + 1
        conference_obj.update_datamap(valid_data)
        conference_obj.save()
        return conference_obj.uid


def remove_conference(session,conference_id,creat_identity_id):
    perm_valid.manager_perm_valid(session,creat_identity_id)
    sql="DELETE l,d FROM meeting_list l LEFT JOIN meeting_detail d " +\
        "ON l.id=d.meeting_id " +\
        "WHERE l.id=%s AND l.creat_identity_id=%s " +\
        "AND l.meeting_status!=1 OR d.meeting_id=%s"
    values=[int(conference_id),int(creat_identity_id),int(conference_id)]
    return model.MeetingList.remove_operation(sql,values)



class ConferenceValid:
    _step_keys=(('short_summary','meeting_name','meeting_address','meeting_time',"region"),
                ('cover','long_summary',))
                #('cover','long_summary'))
    @staticmethod
    def verify(data,step):
        new_data={}
        if step<=0 or step>len(ConferenceValid._step_keys):
            return False
        must_have_keys = ConferenceValid._step_keys[step-1]
        for each in must_have_keys:
            each_obj = data.get(each)
            if each_obj is None:
                return False
            new_data[each]=each_obj
        return new_data


def add_process(session,creat_identity_id,conference_id,process_time,process_content):
    perm_valid.manager_perm_valid(session, creat_identity_id)
    sql = 'INSERT INTO meeting_detail (`time`,meeting_id,`content`) '+ \
          'SELECT %s,%s,%s FROM DUAL WHERE EXISTS(' +\
          'SELECT id FROM meeting_list WHERE creat_identity_id=%s AND id=%s AND meeting_status!=1)'
    values = [process_time,int(conference_id),process_content,int(creat_identity_id),int(conference_id)]
    return model.MeetingDetail.insert_operation(sql,values)


def delete_process(session,creat_identity_id,conference_id,process_id):
    perm_valid.manager_perm_valid(session,creat_identity_id)
    sql = 'DELETE FROM meeting_detail ' +\
          'WHERE id=%s AND meeting_id=%s AND EXISTS(' \
          'SELECT id FROM meeting_list WHERE id=%s AND creat_identity_id=%s AND meeting_status!=1)'
    model.MeetingDetail.submit(sql,[int(process_id),int(conference_id),int(conference_id),int(creat_identity_id)])
    return True


def update_process(session,creat_identity_id,conference_id,process_id,process_time,process_content):
    perm_valid.manager_perm_valid(session, creat_identity_id)
    sql= 'UPDATE meeting_detail SET time=%s,content=%s WHERE id=%s AND EXISTS(' +\
         'SELECT id FROM meeting_list WHERE id=%s AND creat_identity_id=%s AND meeting_status!=1)'
    values = [process_time,process_content,int(process_id),int(conference_id),int(creat_identity_id)]
    model.MeetingDetail.submit(sql,values)
    return True


def get_conference_by_creator(creator_id):
    conference_objs = model.MeetingList.all_objects('meeting_name','cover','meeting_time','meeting_address',"is_checked").filter(creator_id=creator_id,meeting_status=1).order_by("id",desc=True).select()
    return [each_obj.datamap for each_obj in conference_objs]


def get_script_conference_by_creator(creator_id):
    conference_objs = model.MeetingList.all_objects('meeting_name','cover','meeting_status','creat_identity_id').filter(creator_id=creator_id,mt__meeting_status=1).select()
    return_obj=[]
    for each_obj in conference_objs:
        return_obj.append({
            'meeting_name':each_obj.meeting_name,
            'cover':each_obj.cover,
            'step':each_obj.meeting_status-1,
            "id":each_obj.uid,
            "creat_identity_id":each_obj.creat_identity_id
        })
    return return_obj


def transform_conference_status(data):
    meeting_time = data["meeting_time"]
    today=datetime.now().replace(hour=0,minute=0,second=0,microsecond=0)
    tomorrow=today+timedelta(days=1)
    if meeting_time>tomorrow:
        state=1 #报名中
    elif meeting_time<today:
        state=3 #已结束
    else:
        state=2 #进行中
    data['state']=state
    return data


def get_conference_digest(page):
    return_keys=['id','meeting_name','cover','meeting_address','meeting_time']
    sql = 'SELECT id,meeting_name,cover,meeting_address,meeting_time '+\
        'FROM meeting_list ' +\
        'WHERE meeting_status=1 AND is_checked=1 ORDER BY id DESC'
    query_res = model.MeetingList.query(sql)
    return [transform_conference_status(dict(zip(return_keys,each))) for each in query_res]


def get_conference_detail(conference_id):
    return_keys=['id','meeting_name','cover','meeting_address','meeting_time','short_summary','long_summary','meeting_status','is_checked','creat_identity_id','region','reg_count']
    sql = 'SELECT m.id,m.meeting_name,m.cover,m.meeting_address,m.meeting_time,m.short_summary,m.long_summary,m.meeting_status,m.is_checked,m.creat_identity_id,m.region,COUNT(r.id) '+\
        'FROM meeting_list m,meeting_reg r WHERE m.id=r.meeting_id ' +\
        'AND m.id=%s'
    values=[int(conference_id)]
    query_res = model.MeetingList.query(sql,values)
    if not query_res:
        return None
    return transform_conference_status(dict(zip(return_keys,query_res[0])))


def my_attend_status(user_id,conference_id):
    return_keys=['name','sex','id_card','phone','company','status','user_type','meeting_id',
                 'organization','position','email','contact_name','contact_phone','contact_org']
    sql = "SELECT r.name,r.sex,r.id_card,r.phone,r.company,r.`status`,r.user_type,r.meeting_id," +\
          "r.organization,r.position,r.email,m.contact_name,m.contact_phone,m.contact_org " +\
          "FROM meeting_reg r,meeting_list d,meeting_manager m " +\
          "WHERE r.meeting_id=d.id AND d.creat_identity_id=m.id " +\
          "AND r.meeting_id=%s AND r.user_id=%s"
    values = [int(conference_id),int(user_id)]
    res = model.MeetingReg.query(sql,values)
    if res:
        res=res[0]
    else:
        return None
    if res:
        return dict(zip(return_keys,res))
    else:
        return None


def get_conference_process(conference_id):
    process_objs = model.MeetingDetail.all_objects().filter(meeting_id=int(conference_id)).select()
    return [each.datamap for each in process_objs]


def register_invation_code(user_id,invitation_code):
    sql = "UPDATE {0} SET user_id=%s WHERE invitation_code=%s AND user_id=0".format(model.MeetingManager._table)
    values=[int(user_id),invitation_code]
    conn = model.MeetingManager.write()
    cursor = conn.cursor()
    try:
        effect_row = cursor.execute(sql,values)
        cursor.close()
        conn.close()
    except:
        effect_row = 0
        cursor.close()
        conn.close()
    if effect_row!=0:
        return True
    else:
        return False


def have_add_conference_auth(user_id):
    obj = model.MeetingManager.all_objects('contact_name','contact_phone','contact_org').filter(user_id=int(user_id)).select()
    if obj:
        return [each.datamap for each in obj]
    else:
        return False


def apply_for_conference(user_id,conference_id,data,user_type_id):
    new_obj = model.MeetingReg()
    valid_info = (("name",True,"姓名"),("sex",False,""),("id_card",True,"身份证"),("phone",True,"电话"),("company",False,""),
                  ("organization",False,""),("position",False,""),("email",False,""))
    new_data={}
    for field,must,desc in valid_info:
        value =  data.get(field)
        if value:
            new_data[field]=value
        elif must:
            raise ServiceError("need %s" % desc,can_out_put=True)
    new_obj.meeting_id=int(conference_id)
    new_obj.user_id=int(user_id)
    new_obj.user_type=int(user_type_id)
    new_obj.update_datamap(new_data)
    insert_data=new_obj.datamap
    today = datetime.now().replace(hour=0, minute=0, second=0, microsecond=0)+timedelta(days=1)
    sql = 'INSERT INTO meeting_reg ({insert_key}) ' + \
          'SELECT {insert_values} FROM DUAL WHERE EXISTS(' + \
          'SELECT id FROM meeting_list WHERE meeting_status=1 AND is_checked=1 AND meeting_time>%s AND id=%s)'
    insert_values=','.join(['%s']*len(insert_data))
    key_names=[]
    key_values=[]
    for each_key,each_value in insert_data.items():
        key_names.append('`'+each_key+'`')
        key_values.append(each_value)
    sql=sql.format(insert_key=','.join(key_names),insert_values=insert_values)
    values=key_values
    values.extend([today,int(conference_id)])
    try:
        return model.MeetingReg.insert_operation(sql,values)
    except:
        raise ServiceError("may be ukeys")


def submit_for_check(session,user_id,creat_identity_id,conference_id):
    perm_valid.manager_perm_valid(session,creat_identity_id)
    sql = 'UPDATE meeting_list SET meeting_status=1 WHERE creator_id=%s AND id=%s AND creat_identity_id=%s AND meeting_status>1'
    values=[int(user_id),int(conference_id),int(creat_identity_id)]
    return model.MeetingList.update_operation(sql,values)


def get_my_attend_conference(user_id):
    return_keys = ['id','meeting_name','meeting_time','meeting_address','reg_status']
    sql = 'SELECT l.id,l.meeting_name,l.meeting_time,l.meeting_address,r.status reg_status ' +\
          'FROM meeting_list l,meeting_reg r ' +\
          'WHERE l.id=r.meeting_id AND r.user_id=%s'
    values=[int(user_id)]
    res = model.MeetingList.query(sql,values)
    return [dict(zip(return_keys,each)) for each in res]



def sign_up_for_conference(user_id,conference_id):
    sql = 'UPDATE meeting_reg SET status=1 WHERE user_id=%s AND meeting_id=%s'
    values=[int(user_id),int(conference_id)]
    return model.MeetingReg.update_operation(sql,values)
